package com.grj.park.boot.excetion;

import com.grj.park.boot.domain.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.concurrent.atomic.AtomicReference;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    // 处理 MethodArgumentNotValidException 异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public R<String> handleValidationExceptions(MethodArgumentNotValidException ex) {
        AtomicReference<String> key = new AtomicReference<>("");
        AtomicReference<String> errorMessage = new AtomicReference<>("");
        ex.getBindingResult().getAllErrors().forEach((error) -> {
            key.set(((FieldError) error).getField());
            errorMessage.set(error.getDefaultMessage());
        });
        log.error("参数校验失败，参数名：{}, 错误信息：{}", key.get(), errorMessage.get());
        return R.fail(errorMessage.get());
    }


    // 处理其他未捕获的异常
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public R<String> handleException(Exception ex) {
        String message = ex.getMessage();
        log.error(message);
        return R.fail(message.split(":")[0]);
    }

}
